#! /usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) Huoty, All rights reserved
# Author: Huoty <sudohuoty@163.com>
# CreateTime: 2020-01-15 15:25:58


class ArrayStack(object):
    """栈，数组实现"""

    def __init__(self):
        self.items = []

    def __len__(self):
        return len(self.items)

    def __repr__(self):
        return "{}(size={})".format(self.__class__.__name__, len(self))

    def __iter__(self):
        return (item for item in self.items)

    def __contains__(self, item):
        return item in self.items

    def __add__(self, other):
        return self.items + other.items

    def __eq__(self, other):
        return self.items == other.items

    def is_empty(self):
        """判断是否为空"""
        return not self.items

    def push(self, item):
        """加入元素"""
        self.items.append(item)

    def pop(self):
        """弹出元素"""
        return self.items.pop()

    def peek(self):
        """返回栈顶元素"""
        if not self.items:
            raise KeyError("Stack is empty")
        return self.items[-1]

    def clear(self):
        """清空栈"""
        self.items.clear()


if __name__ == "__main__":
    s = ArrayStack()
    s.push('a')
    s.push('b')
    s.push('c')
    print(s)
    for item in s:
        print(item)
    for item in s:
        print(item)
    print("is empty:", s.is_empty())
    print("length:", len(s))
    print("top:", s.peek())
    print("pop action:", s.pop())
    print("pop action:", s.pop())
    print("pop action:", s.pop())
    print("is empty:", s.is_empty())

    try:
        s.pop()
    except Exception as e:
        assert isinstance(e, IndexError)

    try:
        s.peek()
    except Exception as e:
        assert isinstance(e, KeyError)

    s.push('d')
    print(s.items)
